#import "ScalpController.h"
#import "ScalpSSHPublishOperation.h"

ScalpController *_sharedController;

@implementation ScalpController

+(void)load {
    ScalpController *ctrl = [self sharedInstance];
    [[NSNotificationCenter defaultCenter] addObserver:ctrl
                                             selector:@selector(iCalLaunched)
                                                 name:NSApplicationDidFinishLaunchingNotification
                                               object:nil];
}

+(ScalpController *)sharedInstance {
    if (!_sharedController)
        _sharedController = [[self alloc] init];
    return _sharedController;
}

-(BOOL)enabled {
    return enabled;
}

-(void)iCalLaunched {
    NSLog(@"checking");
    NSString *iCalVersion = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleVersion"];
    
    NSURLRequest *mvReq = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://pygmysoftware.com/icalmax-0.7.txt"]
                                           cachePolicy:NSURLRequestReloadIgnoringLocalCacheData
                                       timeoutInterval:5.0];
    NSURLResponse *mvResp = NULL;
    NSData *mvData = [NSURLConnection sendSynchronousRequest:mvReq returningResponse:&mvResp error:NULL];
    NSString *maxVersion = [[[NSString alloc] initWithData:mvData encoding:NSASCIIStringEncoding] autorelease];
    
    if (maxVersion == NULL || [maxVersion isEqualToString:@""] || [maxVersion intValue] == 0) // error loading max version; assume everything is OK
        enabled = YES;
    else if ([iCalVersion intValue] <= [maxVersion intValue])
        enabled = YES;
    else
        enabled = NO;
        
    if (self.enabled) {
        NSLog(@"yes");
        [CALURLPublisher registerPublishOperation:[ScalpSSHPublishOperation class] priority:0];
    } else {
        NSLog(@"no");
        int alertReturn = NSRunAlertPanel(@"Scalp disabled", @"The Scalp plugin has been disabled because it has detected a new version of iCal. This either means that this version of Scalp has been found to be incompatible with this version of iCal or the developer has not tested it yet. If you like, you can check Pygmy Software's Web site for a new version.", @"Check for New Version", @"Don't Check", NULL);
        if (alertReturn == NSAlertDefaultReturn) {
            [[NSWorkspace sharedWorkspace] openURL:[NSURL URLWithString:@"http://pygmysoftware.com/software/scalp/"]];
        }
    }
    NSLog(@"done");
}

@end
